/* eslint-disable @typescript-eslint/restrict-plus-operands */
/* eslint-disable no-var */
import moment, { Moment } from 'moment';
import Base from 'src/models/Base';
export function unix2Moment(unix: number | string): Moment {
  if (typeof unix === 'string') {
    unix = parseInt(unix);
  }
  if (unix > 0) {
    return moment(unix);
  } else {
    return moment();
  }
}
export function fancyTimeFormat(duration: number) {
  // Hours, minutes and seconds
  var hrs = Math.floor(duration / 3600);
  var mins = Math.floor((duration % 3600) / 60);
  var secs = Math.floor(duration % 60);

  // Output like "1:01" or "4:03:59" or "123:03:59"
  var ret = '';

  if (hrs > 0) {
    ret += '' + hrs + ':' + (mins < 10 ? '0' : '');
  }

  ret += '' + mins + ':' + (secs < 10 ? '0' : '');
  ret += '' + secs;
  return ret;
}
export function groupByTime<T extends Base>(items: T[]): Array<T[]> {
  if (items.length > 0) {
    const week: T[] = [];
    const month: T[] = [];
    const eariler: T[] = [];
    if (items.length > 0) {
      items.forEach((item) => {
        if (item.createTimeGroupName === 'week') {
          week.push(item);
        } else if (item.createTimeGroupName === 'month') {
          month.push(item);
        } else {
          eariler.push(item);
        }
      });
    }
    return [week, month, eariler];
  } else {
    return [];
  }
}
export function arrTrans<T>(num: number, arr: Array<T>) {
  // 一维数组转换为二维数组
  const iconsArr: Array<T[]> = [];
  arr.forEach((item, index) => {
    const page = Math.floor(index / num);
    if (!iconsArr[page]) {
      iconsArr[page] = [];
    }
    // eslint-disable-next-line @typescript-eslint/no-unsafe-call
    iconsArr[page].push(item);
  });
  return iconsArr;
}
export function checkAudioContext() {
  return window.AudioContext || window.webkitAudioContext;
}
/**
 *
 * @param videoFile selected video file
 * @param time time percent of a video. eg:0.5 is half time of video's duration
 * @returns
 */
export function getVideoFrame(videoFile: File, time = 0): Promise<string> {
  return new Promise<string>((resolve, reject) => {
    const video = document.createElement('video');
    video.volume = 0;
    const fileURL = URL.createObjectURL(videoFile);
    video.src = fileURL;
    video.onloadedmetadata = (e) => {
      video.currentTime = time * video.duration;
    };
    video.onseeked = (e) => {
      const canvas = document.createElement('canvas');
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      const ctx = canvas.getContext('2d');
      ctx?.drawImage(video, 0, 0, canvas.width, canvas.height);
      resolve(canvas.toDataURL());
    };
    video.onerror = (e) => {
      console.log(e);
      reject(e);
    };
    console.log(video.parentNode);
  });
}
